package cn.turboinfo.fuyang.api.gateway.admin.controller.contract;

import cn.turboinfo.fuyang.api.domain.admin.usecase.contract.ContractTmplSearchUseCase;
import cn.turboinfo.fuyang.api.entity.common.pojo.contract.ContractTmpl;
import cn.turboinfo.fuyang.api.entity.common.pojo.contract.QContractTmpl;
import cn.turboinfo.fuyang.api.gateway.admin.fo.contract.ContractTmplSearchFO;
import cn.turboinfo.fuyang.api.gateway.admin.framework.http.ResponseBodyWrapper;
import cn.turboinfo.fuyang.api.gateway.admin.framework.http.context.AdminRequestContext;
import cn.turboinfo.fuyang.api.gateway.admin.framework.http.fo.LimitDataFO;
import cn.turboinfo.fuyang.api.gateway.admin.framework.http.fo.LimitFO;
import cn.turboinfo.fuyang.api.gateway.admin.framework.http.fo.SortFO;
import cn.turboinfo.fuyang.api.gateway.web.framework.http.annotation.CompanyScope;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import net.sunshow.toolkit.core.qbean.api.request.QRequest;
import net.sunshow.toolkit.core.qbean.api.request.QSort;
import net.sunshow.toolkit.core.qbean.helper.component.request.QBeanSearchHelper;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.validation.Valid;
import java.util.Arrays;

@Slf4j
@RequiredArgsConstructor
@Controller
@ResponseBodyWrapper
@RequestMapping("/admin/contract/template")
public class ContractTmplController {

    private final ContractTmplSearchUseCase contractTmplSearchUseCase;

    @RequiresPermissions("contractTmpl:list")
    @RequestMapping("/search")
    @CompanyScope
    public LimitDataFO<ContractTmpl> list(@Valid ContractTmplSearchFO search, LimitFO page,
                                          SortFO sort, AdminRequestContext context) {

        QRequest request = QBeanSearchHelper.convertQRequest(search);

        Long companyId = context.getCompanyId();

        if (companyId != null && search.getCompanyId() == null) {
            request.filterIn(QContractTmpl.companyId, Arrays.asList(new Long[]{0L, companyId}));
        }

        if (sort.getSortFields() == null) {
            sort.setSortFields(new String[]{QContractTmpl.id + "|" + QSort.Order.ASC.name()});
        }

        ContractTmplSearchUseCase.OutputData outputData = contractTmplSearchUseCase.execute(ContractTmplSearchUseCase.InputData
                .builder()
                .request(request)
                .requestPage(page.toQPage(sort.toQSortList()))
                .build());

        return LimitDataFO.fromQResponse(outputData.getQResponse());
    }

}
